package com.jie.scanbarcode

import android.content.Context
import android.graphics.Point
import android.util.AttributeSet
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.appcompat.widget.AppCompatImageView
import androidx.constraintlayout.widget.ConstraintLayout

/**
 * 对焦View
 */
class FocusImageView : AppCompatImageView {
    private var mFocusImg = NO_ID
    private var mFocusSucceedImg = NO_ID
    private var mFocusFailedImg = NO_ID
    private lateinit var mAnimation: Animation

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView()
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.code_FocusImageView)
        mFocusImg = typedArray.getResourceId(
            R.styleable.code_FocusImageView_code_focus_focusing_id, NO_ID)
        mFocusSucceedImg = typedArray.getResourceId(
            R.styleable.code_FocusImageView_code_focus_success_id, NO_ID)
        mFocusFailedImg = typedArray.getResourceId(
            R.styleable.code_FocusImageView_code_focus_fail_id, NO_ID)
        typedArray.recycle()
    }

    /**
     * 初始化组件
     */
    private fun initView(){
        mAnimation = AnimationUtils.loadAnimation(context, R.anim.code_focusview_show)
        visibility = GONE
    }

    /**
     * 显示对焦图案
     */
    fun startFocus(point: Point) {
        if (mFocusImg == NO_ID || mFocusSucceedImg == NO_ID || mFocusFailedImg == NO_ID) {
            throw RuntimeException("focus image is null")
        }
        //根据触摸的坐标设置聚焦图案的位置
        val params = layoutParams as ConstraintLayout.LayoutParams
        params.topMargin = point.y - measuredHeight / 2
        params.leftMargin = point.x - measuredWidth / 2
        layoutParams = params
        //设置控件可见，并开始动画
        visibility = VISIBLE
        setImageResource(mFocusImg)
        startAnimation(mAnimation)
    }

    /**
     * 聚焦成功回调
     */
    fun onFocusSuccess() {
        setImageResource(mFocusSucceedImg)
        //移除在startFocus中设置的callback，1秒后隐藏该控件
        removeCallbacks(delayHide)
        postDelayed(delayHide, 1000)
    }

    /**
     * 聚焦失败回调
     */
    fun onFocusFailed() {
        setImageResource(mFocusFailedImg)
        //移除在startFocus中设置的callback，1秒后隐藏该控件
        removeCallbacks(delayHide)
        postDelayed(delayHide, 1000)
    }

    /**
     * 延时隐藏组件
     */
    private val delayHide = {
        visibility = GONE
    }

    companion object {
        private const val NO_ID = -1
    }
}